<template>
  <div class="mocks-main-inner">
    <!--听力做题-->
    <mocks-listen v-if="partInfo && partInfo.part_type == 1" :part-info="partInfo"></mocks-listen>
    <!--组合题-->
    <mocks-combination v-if="partInfo && partInfo.part_type == 3" :part-info="partInfo"></mocks-combination>
    <!--写作题-->
    <mocks-write v-if="partInfo && partInfo.part_type == 5" :part-info="partInfo"></mocks-write>
    <!--阅读题-->
    <mocks-read v-if="partInfo && partInfo.part_type == 4" :part-info="partInfo"></mocks-read>
  </div>
</template>

<script>
  import { mapState, mapActions } from 'vuex';
  import checkAnswerAll from '../utils/check_answer_all';
  import MocksListen from './listen';
  import MocksCombination from './combination';
  import MocksWrite from './write'
  import MocksRead from './read'

  export default {
    name: "MocksQuestion",
    componentName: 'MocksQuestion',
    components: {MocksListen, MocksCombination, MocksWrite, MocksRead},
    created () {
    },
    beforeRouteEnter (to, from, next) {
      next(vm => {
        let currentPart = vm.$route.params.currentPart;
        vm.updateCurrentPart(currentPart);
        // 更新头部的上一步的按钮状态
        vm.updateDisabledPrevBtn(false);
      });
    },
    computed: {
      ...mapState([
        'paperInfo',
        'paperId',
        'courseId',
        'paperType',
        'currentPart',
        'totalPart',
        'partInfo'
      ])
    },
    methods: {
      ...mapActions([
        'updateCurrentPart',
        'updateDisabledPrevBtn',
        'updateShowHeaderPart'
      ]),
      /**
       * 检查用户是否已经回答过，如果用户已经回答过，就直接跳过提交答案
       * 可能暂时还用不到
       * @returns {boolean}
       * @private
       */
      _checkUserIsAnswer () {
        if (this.partInfo && this.partInfo.question_list && this.partInfo.question_list.length) {
          let question_list = this.partInfo.question_list;

          for (let i = 0; i < question_list.length; i++) {
            if (!question_list[i].user_is_answer)
              return false;
          }
        }
        return true;
      },
      /**
       * 检查当前试卷是否还有题没有回答
       * @private
       */
      _checkPartAnswerHasEmpty () {
        let $children = this.$children;
        if ($children && $children.length) {
          for (let i = 0; i < $children.length; i++) {
            if ($children[i].$options.componentType == 'paperPartQuestion') {
              if (!$children[i].checkUserAnswer()) {
                return false;
              }
            }
          }
        }
        return true;
      },
      /**
       * 提交当前用户的答案内容
       * @param callback 从app传递过来的回调，用来进行进行页面间的跳转
       * @private
       */
      _doSubmitPartAnswer (callback) {
        let answers = this._getQuestionListAnswer ();
        let _data = {
          paperId: this.paperId,
          courseId: this.courseId,
          answers: JSON.stringify(answers),
          random_string: (typeof random_string == 'string' ? random_string : ''),
          secret_string: (typeof secret_string == 'string' ? secret_string : '')
        };
        let _this = this;
        $.ajax({
          url: 'http://www.ruixinnj.com/report/submit_answer',
          // url: '/api/mocks/submit/part',
          data: _data,
          type: 'post',
          dataType: 'json',
          success: function (response) {
            if (response.status == 1) {
              _this._setUserAnswers(answers);
              callback();
            } else {
              layer.msg(response.msg);
            }
          }
        })
      },
      /**
       * 获取用户的回答结果
       * @private
       */
      _getQuestionListAnswer () {
        let answers = null;
        // getPartAnswer
        let $children = this.$children;
        // debugger;
        if ($children && $children.length) {
          for (let i = 0; i < $children.length; i++) {
            if ($children[i].$options.componentType == 'paperPartQuestion') {
              answers = $children[i].getPartAnswer();
            }
          }
        }
        return answers;
      },
      _setUserAnswers (answers) {
        let questionList = this.partInfo.question_list;
        questionList.forEach((question, index) => {
          question.user_is_answer = true;
          question.user_answer = answers[index] ? answers[index].answer : null;
        });
      },
      submitPaper () {
        let _this = this;
        $.ajax({
          url: 'http://www.ruixinnj.com/report/set_status',
          // url: '/api/mocks/result',
          data: {
            paperId: this.paperId,
            courseId: this.courseId,
            paperType: this.paperType,
            random_string: (typeof random_string == 'string' ? random_string : ''),
            secret_string: (typeof secret_string == 'string' ? secret_string : '')
          },
          type: 'post',
          dataType: 'json',
          success: function (response) {
            if (response.status == 1) {
              let _data = response.data;
              _this.updateShowHeaderPart(false);
              // _this.$router.replace(`/result/${_this.paperId}/1/0`)
              _this.$router.replace(`/result/${_this.paperId}/${_data.result}/${_data.score}`)
            }else {
              layer.msg(response.msg);
            }
          }
        })
      },
      submitAnswer (callback, submitPaper) {
        if (submitPaper) {
          this._doSubmitPartAnswer(() => {
            let _paperHasEmpty = checkAnswerAll(this.paperInfo);
            if (this._checkPartAnswerHasEmpty() || _paperHasEmpty) {
              layer.confirm('<img src="/paper/images/dialog_bg.png" alt="">' +
                '<p>您还有未完成的题目，<br>确认要提交试卷吗？</p>', {title: false}, (index) => {
                // TODO: 进行提交试卷
                this.submitPaper();
                layer.close(index);
              });
            } else {
              layer.confirm('<img src="/paper/images/dialog_bg.png" alt="">' +
                '<p>确认要提交试卷吗？</p>', {title: false}, (index) => {
                // TODO: 进行提交试卷
                this.submitPaper();
                layer.close(index);
              });
            }
          });
        } else {
          if (this._checkPartAnswerHasEmpty()) {
            layer.confirm('<img src="/paper/images/dialog_bg.png" alt="">' +
              '<p>您还有未完成的题，<br>确定要进行下一步吗？</p>', {title: false}, (index) => {
              this._doSubmitPartAnswer(callback);
              layer.close(index);
            });
          } else {
            this._doSubmitPartAnswer(callback);
          }
        }
      },
      submitEndAnswer () {
        this._doSubmitPartAnswer(() => {
          layer.alert('<img src="/paper/images/dialog_bg.png" style="margin-bottom: 15px" alt="">' +
            '<p>倒计时结束，请提交试卷</p>', {title: false, closeBtn: 0}, (index) => {
            this.submitPaper();
            layer.close(index);
          });
        });
      }
    }
  }
</script>
